<template>
  <div class="app-container">
    <el-row>

<!--扫码界面 -->
      <div >
        <el-card>
          <div>
            <el-form ref="form" label-width="70px" :inline="true" class="login-container" :model="form" :rules="rules">
              <h3 class="login_title">手机验证码,获取领券参数</h3>

              <el-form-item label="手机号" prop="CellPhone" ref="phone">
                <el-input v-model="form.phone" placeholder="请输入手机号">
                </el-input>
              </el-form-item>

              <el-form-item label="验证码" prop="code">
                <el-input v-model="form.code" placeholder="请输入验证码">
                  <el-button slot="suffix" :disabled="disabled" @click="getCode">
                    <span class="Time">{{btnTxt}}</span>
                  </el-button>
                </el-input>
              </el-form-item>

              <el-form-item>
                <el-button @click="submit" class="login_button" type="primary" :loading="buttonLoading"> 获 取  </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>
    </el-row>
    <el-card>
      <div slot="header" class="clearfix">
        <span>参数</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="updateOrderLoginStatus">检测参数是否正常</el-button>
      </div>
      <el-button type="primary" v-clipboard:copy="userCookie" v-clipboard:success="onCopySuccess" v-clipboard:error="onCopyError">复制参数</el-button>
      <div v-show="userCookie!=null">
        参数:{{userCookie}}
      </div>
    </el-card>
  </div>
</template>

<script>
import { addAdminOrder, listOrder } from '@/api/mx/order'
import axios from 'axios'
import { cityList, listProvince } from '@/api/cityManagement'
import { checkCookieIsOk, getPhoneLoginResult } from '@/api/jdInfo'

export default {
  name: "hello",
  data() {
    const validatePhone = (rule, value, callback) => {
      // console.log(rule)
      // console.log(value)
      // console.log(callback)
      // 判断输入框中是否输入手机号
      if (!value) {
        callback(new Error('手机号不能为空'))
      }
      //正则表达式进行验证手机号，从1开始，第二位是35789中的任意一位，以9数字结尾
      if (!/^1[35789]\d{9}$/.test(value)) {
        callback(new Error('手机号格式不正确'))
      }
      callback()
    }
    return {
      btnTxt: "获取验证码",
      // 是否禁用  即点击之后一段时间内无法再点击
      disabled: false,
      time: 0,
      form: {
        CellPhone: '',
        VerificationCode: '',
      },
      rules: {
        phone: [
          { required: true, trigger: 'blur', message: '请输入11位手机号'},
          { required: true, trigger: 'blur', min: 11, max: 11, message: '长度不符合'},
          { required: true, trigger: 'blur', validator: validatePhone}
        ],
        code: [
          { required: true, trigger: 'blur', message: '请输入验证码'},
          { required: true, trigger: 'blur', min: 4, max: 8,message: '验证码错误'}
        ],
      },
      userCookie: null,
      buttonLoading: false
    }
  },
  created() {
    this.getList();
    this.getProvince();
    //this.getLoginInfo()
  },
  methods: {
    /** 查询mx订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //获取城市信息
    getProvince(){
      listProvince().then(res=>{
        if (res.code === 200) {
          this.provinceList = res.data
          this.getLoginInfo()

        }
      })
    },
    getCityList(code){

      if (code === null) {
        return
      }
      let obj={}
      obj = this.provinceList.find((item) => { // 这里的provincelist就是上面省的数据
        return item.code === code // 筛选出匹配数据，这里的id是接口数据中的每一项的id
      })
      let data={
        provinceId : obj.id
      }
      //获取城市列表
      cityList(data).then(res=>{
        if (res.code === 200) {
          this.cityList = res.data
        }

      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodsName: null,
        presetTime: null,
        jdAccount: null,
        cookie: null,
        cookieRecordTime: null,
        createTime: null,
        fishAccount: null,
        customerName: null,

      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加mx订单";
    },
    /** 修改按钮操作 */


    /** 导出按钮操作 */
    handleExport() {
      this.download('jd/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    },
    /**获取京东登陆二维码**/

    getLoginORCode() {
      if (this.queryParams.province === null || this.queryParams.province === undefined) {
        this.$message.error('请选择省份')
        return;
      }else if (this.queryParams.city === null || this.queryParams.city === undefined) {
        this.$message.error('请选择城市')
        return
      } else {
        axios.post('/py/getQRcode', this.queryParams).then(response => {
          //const blob = new Blob([response.data], { type: response.headers['content-type'] }); // 创建Blob对象
          //saveAs(blob, 'image.jpg'); // 调用saveAs方法保存文件到本地
          if (response.status === 200) {

            this.url = "data:image/png;base64," +response.data.qrcode

            this.QRCodeKey=response.data.cookies
            this.wlfstk_smdl=response.data.wlfstk_smdl;
            this.proxx=response.data.proxx;
            this.getLoginResult()

          }

        })
          .catch(error => {
            console.log(error);
          });
      }



    },
    //获取登陆结果
    getLoginResult() {
      let data={
        'wlfstk_smdl': this.wlfstk_smdl+'', 'cookies': this.QRCodeKey+'','proxx':this.proxx
      }
      axios.defaults.headers.common['Content-Type'] = 'application/json';
      this.pollingTimer = setInterval(() => {
        axios.post('/py/getresult', data).then(res => {
          console.log(res)
          this.loginStatus = res.data.msg
          this.userCookie=res.data.qrcookies
          if (res.data.code === 200) {
            clearInterval(this.pollingTimer) // 停止轮询
            console.log('请求成功，停止轮询')
            //将用户信息存入数据库中
            let data={
              cookie: this.userCookie,
              activeName: this.queryParams.activeName,
              createUserId: this.queryParams.createUserId
            }
            addAdminOrder(data).then(res=>{
              if (res.code === 200) {
                this.$message.success('获取成功')
                //this.getList();
              }
            })
          }else if (res.data.code === 500) {
            clearInterval(this.pollingTimer) // 停止轮询
            this.loginStatus = '获取失败，请选择您当前所在地区';
            this.$message.error("获取失败，请选择您当前所在地区")
          }
        })
          .catch(error => {
            console.error(error)
          })
      }, 3000) // 每3秒执行一次请求
    },

    beforeDestroy() {
      clearInterval(this.pollingTimer) // 组件销毁前清除定时器
    },
    onCopySuccess(){
      this.$message.success('复制成功')
    },
    onCopyError(){
      this.$message.error('复制失败')
    },
    /**
     * 查看我的订单
     */
    viewMyOrder(){
      this.$router.push('/index');
    },
    /**
     * 从链接中获取信息
     */
    getLoginInfo() {
      let province = this.$route.query.province
      let city = this.$route.query.city
      let createUserId = this.$route.query.createUserId
      let activeName = this.$route.query.activeName
      console.log(province !== 'undefined' && province !== '')
      if (province !== 'undefined' && province !== '') {
        this.queryParams.province = province
        this.getCityList(province)
        if (city !== 'undefined'&&city !== '') {
          this.queryParams.city = city
        }
      }

      if (createUserId !== 'undefined'&& createUserId !== '') {
        this.queryParams.createUserId = createUserId
      }
      this.queryParams.activeName = activeName
      this.getLoginORCode()
      console.log(this.queryParams)
    },


    /**
     * 获取最新登陆状态
     * @param row
     */
    updateOrderLoginStatus(row){
      if (!this.userCookie) {
        this.$message.error('未获取到信息，请选择正确当前所在地区后获取二维码');
        return
      }
      let data={
        cookie: this.userCookie
      }
      checkCookieIsOk(data).then(response => {
        if (response.code === 200) {
          this.$message.success("信息正常")
          this.getList();
        }
      });
    },
    /**
     * 验证码倒计时
     */
    //获取手机验证码方法
    getCode() {
      // 校验手机号码
      if (!this.form.phone) {
        //号码校验不通过
        this.$message({
          message: '请输入手机号',
          type:'warning',
        });
        //正则判断 从1开始，第二位是35789中的任意一位，以9数字结尾
      } else if (!/1[35789]\d{9}/.test(this.form.phone)) {
        // 失去焦点后自动触发校验手机号规则
        this.$message.error("请输入正确的手机号")
      } else {
        this.time = 60;
        this.disabled = true;
        //调用倒计时方法
        this.timer();
        // 封装的axios接口
        var axios = require('axios');
        var data = this.form.phone

        var config = {
          method: 'post',
          url: '/getPhoneCode',
          headers: {
            'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
            'Content-Type': 'text/plain',
            'Accept': '*/*',
            'Host': '52sr147133.goho.co',
            'Connection': 'keep-alive'
          },
          data : data
        };

        axios(config)
          .then(function (res) {
            if (res.code === 200) {
              this.$message({
                message: '验证成功',
                type: 'success',
              })
            } else {
              this.$message({
                message: '发送失败',
                type: 'warning',
              })
            }
          })
          .catch(function (error) {
            console.log(error);
          });
      /*   axios.post('/getPhoneCode', config).then(({data}) => {
          if (data.code === 200) {
            this.$message({
              message: '验证成功',
              type: 'success',
            })
          } else {
            this.$message({
              message: '发送失败',
              type: 'warning',
            })
          }
        }) */
      }
    },
    timer() {
      if (this.time > 0) {
        this.time--;
        // console.log(this.time);
        this.btnTxt = this.time + "s";
        setTimeout(this.timer, 1000);
      } else {
        this.time = 0;
        this.btnTxt = "获取验证码";
        this.disabled = false;
      }
    },
    /**
     * 登陆
     */
    submit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.buttonLoading=true
          getPhoneLoginResult(this.form).then(res => {
            if (res.code === 200) {
              this.$message.success('获取成功')
              this.userCookie = res.data.ck
              this.buttonLoading=false
            }
          }).catch(()=>{this.buttonLoading=false})
        }
      })


    }
  }
};
</script>

<style  scoped>
.login-container {
  border: 1px solid #eaeaea;

  border-radius: 15px;
  box-shadow: 0 0 25px #cac6c6;
  background-color: #ffffff;
}

.el-input__inner {
  width: 100%; /* 修改为适当的宽度值，例如固定像素或百分比 */
  border: 0;
  border-bottom: 1px solid;
}

.el-button {
  border: 0;
}

.span {
  margin-left: 50px;
}

.login_title {
  text-align: center;
  margin-bottom: 40px;
  color: #505458;
}

.el-input {
  width: 198px;
}

.login_button {
  margin-left: 105px;
  margin-top: 10px;
}

.time {
  width: 20px;
}

</style>
